/*
 * InputEventMgr.cpp
 *
 *  Created on: 2021年9月6日
 *      Author: vicent-PC
 */

#define LOG_TAG "InputEventMgr"

#include "esp_log.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/task.h"
#include "freertos/timers.h"
#include "iot_button.h"
#include "stdio.h"

#include "InputEventMgr.h"
#include <Trace.h>

#define BUTTON_IO_NUM 9
#define BUTTON_ACTIVE_LEVEL 0
static const char* TAG_BTN = "BTN_TEST";

InputEventMgr *InputEventMgr::m_pInstance = nullptr;
static InputEventMgr* gpInputEventMgr = nullptr;

void button_press_down_cb(void* arg) {
    LOGI("button_press_down_cb, heap: %d\n",
                   esp_get_free_heap_size());
    // ESP_LOGI(TAG, "BTN%d: BUTTON_PRESS_DOWN",
    // get_btn_index((button_handle_t)arg));
    if (gpInputEventMgr != nullptr) {
        gpInputEventMgr->dispatch(0);
    }
}

void button_press_5s_cb(void* arg) {
    ESP_EARLY_LOGI(TAG_BTN, "press 5s, heap: %d\n", esp_get_free_heap_size());
}

void button_test() {
    // printf("before btn init, heap: %d\n", esp_get_free_heap_size());
    button_config_t cfg = {
        .type = BUTTON_TYPE_GPIO,
        .gpio_button_config = {
                .gpio_num = 9,
                .active_level = 0,
            },
    };

    button_handle_t btn_handle = iot_button_create(&cfg);

    iot_button_register_cb(btn_handle, BUTTON_PRESS_DOWN, button_press_down_cb);

    // printf("after btn init, heap: %d\n", esp_get_free_heap_size());
}

InputEventMgr::InputEventMgr() : mReciever(nullptr) {
    // TODO Auto-generated constructor stub
}

InputEventMgr::~InputEventMgr() {
    // TODO Auto-generated destructor stub
}

void InputEventMgr::init() { gpInputEventMgr = this; }

void InputEventMgr::registerMgr() { button_test(); }

void InputEventMgr::registerReciever(Activity* activity) {
    TRACE_B();
    mReciever = activity;
}

void InputEventMgr::dispatch(int key) {
    TRACE_B();
    if (mReciever != nullptr) {
        mReciever->onEvent();
    }
}

void InputEventMgr::deInit() {
    gpInputEventMgr = nullptr;
}
